/**
 * 设备检测和界面切换逻辑
 * 自动检测设备类型并重定向到相应的界面
 */

class DeviceDetector {
    constructor() {
        this.deviceInfo = this.detectDevice();
        this.init();
    }

    /**
     * 检测设备类型和特性
     */
    detectDevice() {
        const userAgent = navigator.userAgent.toLowerCase();
        const screenWidth = window.screen.width;
        const screenHeight = window.screen.height;
        const pixelRatio = window.devicePixelRatio || 1;
        
        // 检测设备类型
        const isMobile = /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(userAgent);
        const isTablet = /(ipad|tablet|(android(?!.*mobile))|(windows(?!.*phone)(.*touch))|kindle|playbook|silk|(puffin(?!.*(IP|AP|WP))))/i.test(userAgent);
        const isIOS = /ipad|iphone|ipod/.test(userAgent);
        const isAndroid = /android/.test(userAgent);
        
        // 检测屏幕尺寸类别
        const isLargeScreen = screenWidth >= 1200 || screenHeight >= 1200;
        const isMediumScreen = screenWidth >= 768 && screenWidth < 1200;
        const isSmallScreen = screenWidth < 768;
        
        // 检测触控支持
        const hasTouchSupport = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
        
        // 检测方向
        const isLandscape = screenWidth > screenHeight;
        const isPortrait = screenHeight > screenWidth;
        
        return {
            userAgent,
            screenWidth,
            screenHeight,
            pixelRatio,
            isMobile,
            isTablet,
            isIOS,
            isAndroid,
            isLargeScreen,
            isMediumScreen,
            isSmallScreen,
            hasTouchSupport,
            isLandscape,
            isPortrait,
            // 推荐的界面类型
            recommendedInterface: this.getRecommendedInterface({
                isMobile,
                isTablet,
                isLargeScreen,
                isMediumScreen,
                isSmallScreen,
                screenWidth,
                screenHeight
            })
        };
    }

    /**
     * 根据设备特性推荐界面类型
     */
    getRecommendedInterface(device) {
        // URL参数强制指定界面类型
        const urlParams = new URLSearchParams(window.location.search);
        const forceMode = urlParams.get('mode');
        if (forceMode === 'control' || forceMode === 'display' || forceMode === 'auto') {
            return forceMode;
        }

        // 大屏设备推荐显示界面
        if (device.isLargeScreen && !device.isMobile) {
            return 'display';
        }
        
        // 手机和小屏平板推荐控制界面
        if (device.isMobile || (device.isTablet && device.isSmallScreen)) {
            return 'control';
        }
        
        // 中等尺寸平板根据方向决定
        if (device.isTablet && device.isMediumScreen) {
            return device.isLandscape ? 'display' : 'control';
        }
        
        // 默认自适应界面
        return 'auto';
    }

    /**
     * 初始化设备检测逻辑
     */
    init() {
        // 检查当前页面是否需要重定向
        this.checkRedirection();
        
        // 监听屏幕方向变化
        window.addEventListener('orientationchange', () => {
            setTimeout(() => {
                this.deviceInfo = this.detectDevice();
                this.handleOrientationChange();
            }, 100);
        });
        
        // 监听窗口大小变化
        window.addEventListener('resize', () => {
            this.deviceInfo = this.detectDevice();
            this.handleResize();
        });
        
        // 添加设备信息到页面
        this.addDeviceInfoToPage();
    }

    /**
     * 检查是否需要重定向到其他界面
     */
    checkRedirection() {
        const currentPage = this.getCurrentPageType();
        const recommended = this.deviceInfo.recommendedInterface;
        
        // 检查URL参数是否禁用重定向
        const urlParams = new URLSearchParams(window.location.search);
        const mode = urlParams.get('mode');
        if (mode === 'auto') {
            console.log('设备检测: 检测到mode=auto参数，禁用自动重定向');
            return;
        }
        
        // 如果当前页面类型与推荐类型不匹配，进行重定向
        if (recommended !== 'auto' && currentPage !== recommended && currentPage !== 'index') {
            this.redirectToInterface(recommended);
        }
    }

    /**
     * 获取当前页面类型
     */
    getCurrentPageType() {
        const path = window.location.pathname;
        if (path.includes('mobile-control')) {
            return 'control';
        } else if (path.includes('display-screen')) {
            return 'display';
        } else {
            return 'index';
        }
    }

    /**
     * 重定向到指定界面
     */
    redirectToInterface(interfaceType) {
        const baseUrl = window.location.origin + window.location.pathname.replace(/\/[^/]*$/, '');
        let targetUrl;
        
        switch (interfaceType) {
            case 'control':
                targetUrl = `${baseUrl}/mobile-control.html`;
                break;
            case 'display':
                targetUrl = `${baseUrl}/display-screen.html`;
                break;
            default:
                targetUrl = `${baseUrl}/index.html`;
        }
        
        // 保留URL参数
        const urlParams = new URLSearchParams(window.location.search);
        if (urlParams.toString()) {
            targetUrl += '?' + urlParams.toString();
        }
        
        console.log(`设备检测: 重定向到 ${interfaceType} 界面`, targetUrl);
        window.location.href = targetUrl;
    }

    /**
     * 处理屏幕方向变化
     */
    handleOrientationChange() {
        const event = new CustomEvent('deviceOrientationChange', {
            detail: {
                deviceInfo: this.deviceInfo,
                orientation: this.deviceInfo.isLandscape ? 'landscape' : 'portrait'
            }
        });
        window.dispatchEvent(event);
    }

    /**
     * 处理窗口大小变化
     */
    handleResize() {
        const event = new CustomEvent('deviceResize', {
            detail: {
                deviceInfo: this.deviceInfo,
                screenWidth: this.deviceInfo.screenWidth,
                screenHeight: this.deviceInfo.screenHeight
            }
        });
        window.dispatchEvent(event);
    }

    /**
     * 添加设备信息到页面（调试用）
     */
    addDeviceInfoToPage() {
        // 只在开发模式下显示
        const urlParams = new URLSearchParams(window.location.search);
        if (urlParams.get('debug') === 'true') {
            const debugInfo = document.createElement('div');
            debugInfo.id = 'device-debug-info';
            debugInfo.style.cssText = `
                position: fixed;
                top: 10px;
                left: 10px;
                background: rgba(0, 0, 0, 0.8);
                color: white;
                padding: 10px;
                border-radius: 5px;
                font-size: 12px;
                font-family: monospace;
                z-index: 9999;
                max-width: 300px;
            `;
            
            debugInfo.innerHTML = `
                <strong>设备信息:</strong><br>
                类型: ${this.deviceInfo.isMobile ? '手机' : this.deviceInfo.isTablet ? '平板' : '桌面'}<br>
                屏幕: ${this.deviceInfo.screenWidth}x${this.deviceInfo.screenHeight}<br>
                方向: ${this.deviceInfo.isLandscape ? '横屏' : '竖屏'}<br>
                触控: ${this.deviceInfo.hasTouchSupport ? '支持' : '不支持'}<br>
                推荐界面: ${this.deviceInfo.recommendedInterface}<br>
                当前页面: ${this.getCurrentPageType()}
            `;
            
            document.body.appendChild(debugInfo);
        }
    }

    /**
     * 获取设备信息
     */
    getDeviceInfo() {
        return this.deviceInfo;
    }

    /**
     * 创建界面选择器
     */
    createInterfaceSelector() {
        const selector = document.createElement('div');
        selector.id = 'interface-selector';
        selector.style.cssText = `
            position: fixed;
            bottom: 20px;
            right: 20px;
            background: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 15px;
            border-radius: 10px;
            z-index: 9999;
            font-size: 14px;
        `;
        
        selector.innerHTML = `
            <div style="margin-bottom: 10px;"><strong>选择界面:</strong></div>
            <button onclick="window.location.href='index.html'" style="margin: 2px; padding: 5px 10px; border: none; border-radius: 3px; cursor: pointer;">自适应</button><br>
            <button onclick="window.location.href='mobile-control.html'" style="margin: 2px; padding: 5px 10px; border: none; border-radius: 3px; cursor: pointer;">手机控制</button><br>
            <button onclick="window.location.href='display-screen.html'" style="margin: 2px; padding: 5px 10px; border: none; border-radius: 3px; cursor: pointer;">大屏显示</button>
        `;
        
        return selector;
    }
}

// 全局设备检测器实例
window.deviceDetector = new DeviceDetector();

// 导出供其他模块使用
if (typeof module !== 'undefined' && module.exports) {
    module.exports = DeviceDetector;
}